package com.joyoung.common.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.lang.reflect.Method;

/**
 * A utility of Android device and app version
 * Created by zhangdroid on 2017/7/21.
 * <p>
 * 注意：官方不推荐使用：Android 标识符的使用原则，原则 1：避免使用硬件标识符。https://developer.android.com/training/articles/user-data-ids
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public final class DeviceUtil {

    private DeviceUtil() {}

    public static DisplayMetrics getDisplayMetrics(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        if (windowManager == null) {
            return null;
        }
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    /**
     * 获取屏幕宽度
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics displayMetrics = getDisplayMetrics(context);
        return displayMetrics == null ? 0 : displayMetrics.widthPixels;
    }

    /**
     * 获取屏幕高度
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics displayMetrics = getDisplayMetrics(context);
        return displayMetrics == null ? 0 : displayMetrics.heightPixels;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    /**
     * 获得当前应用包名
     *
     * @param context 上下文对象
     */
    public static String getPackageName(Context context) {
        return context.getApplicationContext().getPackageName();
    }

    /**
     * 获得当前应用版本号（code）
     *
     * @param context 上下文对象
     */
    public static int getVersionCode(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        if (packageInfo == null) {
            return -1;
        }
        return packageInfo.versionCode;
    }

    /**
     * 获得当前应用版本编号（name）
     *
     * @param context 上下文对象
     */
    public static String getVersionName(Context context) {
        PackageInfo packageInfo = getPackageInfo(context);
        return packageInfo == null ? null : packageInfo.versionName;
    }

    /**
     * 获取应用名称
     *
     * @param context 上下文对象
     */
    public static String getAppName(Context context) {
        return (String) context.getApplicationInfo().loadLabel(getPackageManager(context));
    }

    public static PackageManager getPackageManager(Context context) {
        return context.getApplicationContext().getPackageManager();
    }

    public static PackageInfo getPackageInfo(Context context) {
        PackageManager packageManager = getPackageManager(context);
        try {
            return packageManager.getPackageInfo(getPackageName(context), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getMetaData(Context context, String name) {
        try {
            ApplicationInfo ai = getPackageManager(context).getApplicationInfo(getPackageName(context), PackageManager.GET_META_DATA);
            return ai.metaData.getString(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static TelephonyManager getTelephonyManager(Context context) {
        return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    }

    /**
     * 跳转设置中应用详情页面
     *
     * @param activity 上下文对象
     */
    public static void showAppDetail(Activity activity, int requestCode) {
        Uri packageURI = Uri.parse("package:" + getPackageName(activity));
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 获取设备id
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getDeviceId(Context context) {
        return getTelephonyManager(context).getDeviceId();
    }

    /**
     * 获取手机号码
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static String getPhoneNumber(Context context) {
        return getTelephonyManager(context).getLine1Number();
    }

    /**
     * 获取Android id
     */
    @SuppressLint("HardwareIds")
    public static String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }


    // 官方不推荐使用：Android 标识符的使用原则，原则 1：避免使用硬件标识符。https://developer.android.com/training/articles/user-data-ids
    @SuppressLint("HardwareIds")
    public static String getMacAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager == null) {
            return "";
        }
        return wifiManager.getConnectionInfo().getMacAddress();
    }

    /** 获取SN， 主要给商米使用 */
    @SuppressLint("HardwareIds")
    @SuppressWarnings("unchecked")
    public static String getSn() {
        try {
            Class c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            return (String) get.invoke(c, "ro.serialno");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
